<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #page span {
            padding-left:10px;
            padding-right:10px;
            cursor: pointer;
            
        }
    </style>
</head>

<body>


    <input id="search" type="text" />
    <button id="btnSearch">搜索姓名</button>
    
    <form>
        <label>
            用户名
            <input id="username" type="text" />
        </label>
        <label>
            年龄
            <input id="age" type="text" />
        </label>
        <label>
            邮箱
            <input id="email" type="text" />
        </label>
        <input id="submit" type="button" value="提交" />
    </form>
    <ul id="list">
    </ul>
    <div id="count">
        0
    </div>
    <div id="page">
        
    </div>

    <script src="libs/zepto/zepto.js"></script>
    <script src="libs/zepto/touch.js"></script>
    <script src="libs/zepto/event.js"></script>
    <script>
        var db;
        var objectStore;
        var advancing = true;
        var n = 0;
        var page = 0;
        function connectDb() {
            var request = window.indexedDB.open('info');

            request.onerror = function (event) {
                console.log('连接错误', event);
            }

            request.onsuccess = function (event) {
                //可以拿到数据库对象
                db = request.result;
                getCount();
                getDataRender();
            }
            //如果指定的版本号，大于数据库的实际版本号，就会发生数据库升级事件upgradeneeded
            request.onupgradeneeded = async function (event) {
                db = event.target.result;

                var objectStore = await db.createObjectStore('user', { keyPath: 'id', autoIncrement: true });

                objectStore.createIndex('name', 'name', { unique: false });
                objectStore.createIndex('age', 'age', { unique: false });
                objectStore.createIndex('email', 'email', { unique: false });

            }
        }
        //连接数据库
        connectDb();

        //点击提交表单
        $("#submit").on("click", function (e) {
            var username = $('#username').val();
            var age = $('#age').val();
            var email = $('#email').val();
            n++;
            var request = db.transaction(['user'], 'readwrite')
                .objectStore('user')
                .add({ name: username+n, age: age, email: email });
            request.onsuccess = function (e) {
                console.log('记录填加成功');

                getDataRender();
            }
            request.onerror = function (e) {
                console.log('记录填加失败', e);
            }
        })

        //删除记录
        function deleteFn(id) {
            var request = db.transaction(['user'], 'readwrite')
                .objectStore('user')
                .delete(id);

            request.onsuccess = function () {
                console.log(`id为${id}的记录删除成功`);
            }

            request.onerror = function (e) {
                console.log(`id为${id}的记录删除失败${e}`);
            }
        }

        //删除按扭加一个点击事件
        $('#list').on("click", "#delete", function (e) {
            console.log('<--delete');
            var id = parseInt(e.currentTarget.dataset.id, 10);
            deleteFn(id);
            getDataRender();
        })

        //获取总数条数

        function getCount() {
            var objectStore = db.transaction('user').objectStore('user');
            var request = objectStore.openCursor();
            var counter = 0;
            request.onsuccess = function (e) {
                var cursor = event.target.result;
                console.log(cursor, '<---cursor');
                if (cursor) {
                    counter++;
                    cursor.continue();
                } else {
                    console.log(counter, '<----counter');
                    var pCount = counter% 10 == 0?counter/ 10: Math.ceil(counter/ 10);
                    console.log(pCount, '<-----p');

                    for(var i = 0; i<4; i++) {
                        $('#page').append(`<span data-page=${i}>${i+1}</span>`);
                    }
                    console.log('没有更多数据了！');
                }
            }

        }
        //获取数据并渲染页面
        function getDataRender() {
            var counter = 0;
            var limit = counter+10;
            var objectStore = db.transaction('user').objectStore('user');
            // var keyRangeValue = IDBKeyRange.bound(7, 12);
            var keyRangeValue = IDBKeyRange.only("30");
            var request = objectStore.openCursor(keyRangeValue);


            var html = '';
            $('#list').html(html);

            request.onsuccess = function (e) {
                var cursor = event.target.result;

                if (cursor) {
                    if (advancing === true && page != 0) {
                    // if (advancing === true ) {
                        console.log(1);
                        cursor.advance(page * limit);
                        advancing = false;
                       
                    } else {
                        console.log(2);

                        html = `<li>
                            ${cursor.value.name}---${cursor.value.age}---${cursor.value.email} <button data-id=${cursor.key} id="delete">删除</button> <button  data-id=${cursor.key} id="edit">修改</button> <input placeholder="修改姓名" text="text"  />
                        </li>`;

                        $('#list').append(html);

                        // console.log(counter, 'counter');
                        counter++;
                        if (counter < limit) {
                            cursor.continue();
                        }
                      
                    }



                } else {
                    console.log('没有更多数据了！');
                }
            }

            request.onerror = function (e) {
                console.log('读取数据失败', e);
            }
        }

        //修改记录
        function editDb(id, username) {
            // var request = db.transaction(['user'], 'readwrite')
            //     .objectStore('user')
            //     .put({ id: id, name: username,age,email});

            var transaction = db.transaction(['user'], 'readwrite');
            var objectStore = transaction.objectStore('user');
            var request = objectStore.get(id);

            request.onsuccess = function (e) {
                var result = request.result;
                result.name = username;

                var updatehandle = objectStore.put(result);

                updatehandle.onsuccess = function () {
                    getDataRender();
                }

                updatehandle.onerror = function (e) {
                    console.log('更新失败', e);
                }





                console.log("修改成功");
            }

            request.onerror = function (e) {
                console.log('记录修改不了', e);
            }

        }

        //给修改按扭填加点击事件
        $('#list').on("click", "#edit", function (e) {
            var id = parseInt(e.currentTarget.dataset.id, 10);
            var name = e.currentTarget.nextElementSibling.value;

            editDb(id, name);
        })

        //分页事键 
        $('#page').on("click", "span", function (e) {
            console.log(e.currentTarget.dataset.page,'<--e.currentTarget.dataset.page');
            
            advancing= true;
            page = parseInt(e.currentTarget.dataset.page, 10);
            getDataRender();
        })

        function searchFn(value) {
            var transaction = db.transaction(['user'], 'readwrite');
            var objectStore = transaction.objectStore('user');
            var index = objectStore.index('name');
            var request = index.get(value);

            request.onsuccess = function (e) {
                var result=e.target.result;
                console.log(result);
            }

            request.onerror = function () {
                console.log('有错误');
            }
        }

        //搜索
        $('#btnSearch').on('click', function (e) {            
            searchFn(e.currentTarget.previousElementSibling.value);
        })

    </script>
</body>

</html>